
/*
 Copyright (C) 2011 James Coliz, Jr. <maniacbug@ymail.com>
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.
 */

/**
 * @file sleep.cpp 
 *
 * Sleep helpers, definitions
 */

#include "RF24Network_config.h"
#include <avr/sleep.h>
#include "sleep.h" 

sleep_c Sleep;

/******************************************************************/

void sleep_c::begin(wdt_prescalar_e prescalar_in,short cycles, short ind)
{
  sleep_cycles_remaining = cycles;
  sleep_cycles_per_transmission = cycles;


  uint8_t prescalar = min(9,(uint8_t)prescalar_in);
  uint8_t wdtcsr = prescalar & 7;
  if ( prescalar & 8 )
      wdtcsr |= _BV(WDP3);

  MCUSR &= ~_BV(WDRF);
  WDTCSR = _BV(WDCE) | _BV(WDE);
  WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE);

  if ((indicator = ind) == 0) return;
  
  led_brightness = 20*255/100;
  
  pinMode(indicator, OUTPUT);
//  digitalWrite(indicator,HIGH);
  analogWrite(indicator, led_brightness);

}

/******************************************************************/

void sleep_c::go(bool doubleBlink)
{
  if (indicator) digitalWrite(indicator,LOW);
  
  while( sleep_cycles_remaining-- )
  {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN); 
    sleep_mode();
    blinkLED();
    if (doubleBlink){
      delay(50);
      blinkLED();
    }
  }
  
  sleep_cycles_remaining = sleep_cycles_per_transmission;
  
  if (indicator) analogWrite(indicator, led_brightness); //digitalWrite(indicator,HIGH); 
  
}

ISR(WDT_vect) {
}


/*******************************************************************/
void sleep_c::blinkLED(){
  
  if (!indicator) return;
  analogWrite(indicator, led_brightness); //digitalWrite(indicator,HIGH);
  delay(10);
  digitalWrite(indicator,LOW);
}


/*******************************************************************/
void sleep_c::led(boolean state){
  digitalWrite(indicator, state);
}
  

// vim:ai:cin:sts=2 sw=2 ft=cpp
